#!/bin/sh

#
# MikoPBX - free phone system for small business
# Copyright © 2017-2023 Alexey Portnov and Nikolay Beketov
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License along with this program.
# If not, see <https://www.gnu.org/licenses/>.
#


# Function to display the help message
display_help() {
    echo "Usage: $0 <subcommand> [options]"
    echo
    echo "Subcommands:"
    echo "  services <action>   Manage PBX services"
    echo "    - stop-all         Stop all PBX services"
    echo "    - start-all        Start all PBX services"
    echo "    - restart-all      Restart all PBX services"
    echo "  service <name>      Kill a specific PBX service"
    echo "  debug <name> <ip>   Debug a specific script"
    echo "  xdebug <action> <ip>   Debug whole system"
    echo "    - enable-cli        Start CLI scripts debug session"
    echo "    - enable-www        Start WEB scripts debug session"
    echo "    - enable-agi        Start Asterisk scripts debug session"
    echo "  cron <action>       Manage cron"
    echo "    - stop             Stop cron"
    echo "    - restart          Restart cron"
    echo "    - start            Start cron"
    echo "    - show             Show the status of cron"
    echo
    echo "Examples:"
    echo "  $0 services start-all"
    echo "  $0 service php-worker"
    echo "  $0 debug WorkerApiCommands 192.168.1.2"
    echo "  $0 debug WorkerApiCommands docker.for.mac.localhost"
    echo "  $0 cron show"
    echo "  $0 xdebug enable-www docker.for.mac.localhost"
    echo "  $0 xdebug enable-agi 192.168.1.2"
    echo
}

# Check if help is requested or no subcommand provided
if [ "$1" = "help" ] || [ -z "$1" ]; then
    display_help
    exit 0
fi


# First command line argument is treated as a subcommand
subcmd=$1;

# Get the name of the safe script from the cron jobs
safeScript=$(crontab -l | cut -d ' ' -f8 | grep Safe);

# Case switch for the subcommand
case "${subcmd}" in
services)
   # Second command line argument is treated as an action
   action=$2;
   # Case switch for the action when subcommand is services
   case "${action}" in
   stop-all)
      # Get process IDs (PIDs) of PHP Worker services
      pids=$(ps | grep php | grep Worker | cut -d ' ' -f1);

      # If PIDs exist, kill the processes
      if [ "${pids}x" != "x" ];then
        echo 'Killing all PBX services.';
        kill "$pids";
      else
        echo 'PBX services not started.';
      fi
      ;;
   start-all)
     # If safe script exists, start it
     if [ -f "$safeScript" ]; then
       /usr/bin/php -f "$safeScript" start
     else
        echo 'Safe script not found.';
     fi
     ;;
   restart-all)
     # If safe script exists, restart it
     if [ -f "$safeScript" ]; then
       /usr/bin/php -f "$safeScript" restart
     else
        echo 'Safe script not found.';
     fi
     ;;
  esac
  ;;
service)
  # Get PIDs of specific service passed as second argument
  pids=$(ps | grep "$2" | grep -v grep | grep -v "$0" | cut -d ' ' -f1);

  # If PIDs exist, kill the service
  if [ "${pids}x" != "x" ];then
    echo "Killing PBX service ${2}.";
    echo "${pids}" | xargs kill
  else
    echo "PBX service ${2} not started.";
  fi
  ;;
debug)
  # Prepare for debugging specific script passed as second argument
  pbxConsole="$0";
  scriptName="$2";
  ipDebugger="$3";

  # Find the file to debug
  pathToFile=$(find /usr/www/src/ -name "${scriptName}.php")
  if [ ! -f "$pathToFile" ];then
    echo "File ${scriptName}.php not found.";
    exit 2;
  fi

  # Stop cron and specific service
  "${pbxConsole}" cron stop;
  "${pbxConsole}" service "${scriptName}" stop;

  # Configure xdebug
  export XDEBUG_CONFIG="remote_enable=1 remote_mode=req remote_autostart=0 remote_port=9000 remote_host=${ipDebugger} remote_connect_back=0";

  # Enable xdebug in PHP if it's not enabled
  if [ ! -f /etc/php.d/15-xdebug.ini ]; then
    cp /etc/php.d/15-xdebug.ini.disabled /etc/php.d/15-xdebug.ini;
    sed -i "s/xdebug.remote_host=.*/xdebug.remote_host=${ipDebugger}/" /etc/php.d/15-xdebug.ini;
  fi;

  # Start the PHP script with xdebug enabled
  php -f "$pathToFile" start;
  ;;

xdebug)
    # Handle actions related to xdebug
    pbxConsole="$0";
    action=$2;
    ipDebugger="$3";
    case "${action}" in
      enable-cli)
        echo "Renaming 15-xdebug.ini.disabled to 15-xdebug.ini ..."
        echo "Changing xdebug.remote_host to address ${ipDebugger} ..."
        sed "s/xdebug.remote_host=.*/xdebug.remote_host=${ipDebugger}/" /etc/php.d/15-xdebug.ini.disabled > /etc/php.d/15-xdebug.ini
        echo "Done"
        ;;
      enable-www)
        echo "Renaming 15-xdebug.ini.disabled to 15-xdebug.ini ..."
        echo "Changing xdebug.remote_host to address ${ipDebugger} ..."
        sed "s/xdebug.remote_host=.*/xdebug.remote_host=${ipDebugger}/" /etc/php.d/15-xdebug.ini.disabled > /etc/php.d/15-xdebug.ini
        echo "killing the php-fpm processes ..."
        killall php-fpm
        sleep 5;
        echo "Restarting the php-fpm daemon ..."
        php-fpm -c /etc/php.ini
        echo "Done"
        ;;
      enable-agi)
        echo "Restarting the asterisk daemon ..."
        killall safe_asterisk
        killall asterisk
        "${pbxConsole}" enable-cli ${ipDebugger}
        nohup safe_asterisk -f > /dev/null 2>&1 &
        echo "Done"
        ;;
    esac
    ;;
cron)
  # Handle actions related to cron
  action=$2;
  case "${action}" in
    stop)
      # If cron is running, kill it
      ps | grep -v grep | grep crond > /dev/null;
      result=$?;
      if [ "$result" = "0" ];then
        echo 'Killing cron.';
        killall crond;
      else
        echo 'Cron not started.';
      fi
      ;;
    restart)
       # Stop cron and then start it
      pbx-console cron stop;
      echo 'Starting cron.';
      /usr/sbin/crond -L /dev/null -l 8
      ;;
    start)
      # If cron is not running, start it
      ps | grep -v grep | grep crond > /dev/null;
      result=$?;
      if [ "$result" = "1" ];then
        echo 'Starting cron.';
        /usr/sbin/crond -L /dev/null -l 8
      else
        echo 'Cron already started.';
      fi
      ;;
    show)
      # Show the status of cron
      ps | head -n 1;
      ps | grep crond | grep -v grep;
      ;;
  esac
  ;;
esac